package com.mylib.libcore.utils;

import android.app.AppOpsManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;


import com.mylib.libcore.R;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import static android.app.PendingIntent.getActivity;


/**
 * 通知栏工具类
 */
public class NotificationUtil {

    private static final int downloadNotifcationId = 0x4316;


    /**
     * 显示通知
     * @param context 上下文
     * @param title 标题
     * @param content 内容
     * @param uri 跳转uri
     */
    public static void showNotification(Context context, int notificationId, String title, String content, String uri) {
        try {
            String packageName = AppUtil.getPackageInfo(context).packageName;
            NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, packageName);
            builder.setAutoCancel(true);
            Notification notification=null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                //ChannelId为"1",ChannelName为"Channel1"
                NotificationChannel channel = new NotificationChannel(packageName, packageName, NotificationManager.IMPORTANCE_DEFAULT);
                channel.enableVibration(true);
                channel.setSound(null, null);
                manager.createNotificationChannel(channel);
                builder.setAutoCancel(true)
                        .setOngoing(false)
                        .setShowWhen(true)
                        .setSmallIcon(R.drawable.app_logo)
                        .setContentTitle(title)
                        .setOnlyAlertOnce(true) //
                        .setContentText(content)
                        .setDefaults(Notification.DEFAULT_VIBRATE); // 默认振动
                Intent intent = new Intent();
                if (!StrUtil.isEmpty(uri)) {
                    intent.setData(Uri.parse(uri));
                }
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                PendingIntent pendingIntent = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                builder.setContentIntent(pendingIntent);
                notification = builder.build();// 获取一个Notification
            }else {
                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
                        .setAutoCancel(true)
                        .setContentTitle(title)
                        .setContentText(content)
                        .setSmallIcon(R.drawable.app_logo)
                        .setOngoing(false)
                        .setChannelId("1");//无效
                Intent intent = new Intent();
                if (!StrUtil.isEmpty(uri)) {
                    intent.setData(Uri.parse(uri));
                }
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                PendingIntent pendingIntent = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                builder.setContentIntent(pendingIntent);
                notification = notificationBuilder.build();

            }

            manager.notify(notificationId, notification);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 展示下载成功通知
     *
     * @param context               上下文
     * @param file                  下载的apk文件
     * @param notificationIconResId 通知图标资源id
     * @param notificationTitle     通知标题
     * @param isCanClear            通知是否可被清除
     */
    public static void showDownloadSuccessNotification(Context context, File file, Bitmap largeIcon, int notificationIconResId, String notificationTitle, String notificationContent, boolean isCanClear) {
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);


        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            //ChannelId为"1",ChannelName为"Channel1"
            NotificationChannel channel = new NotificationChannel("1",
                    "Channel1", NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true); //是否在桌面icon右上角展示小红点
            channel.setLightColor(Color.GREEN); //小红点颜色
            channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
            manager.createNotificationChannel(channel);
        }

        Intent installIntent = new Intent();
        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        if("apk".equals(FileUtil.getExtensionName(file.getName()))) {
            installIntent.setAction(Intent.ACTION_VIEW);
            Uri uri = FileUtil.getUri(context, file);
            installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            installIntent.setAction(Intent.ACTION_SEND);
            installIntent.putExtra(Intent.EXTRA_STREAM, FileUtil.getUri(context, file));
            installIntent.setType("*/*");
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "1"); //与channelId对应
        builder.setAutoCancel(true)
                .setShowWhen(true)
                .setOngoing(false)
                .setSmallIcon(notificationIconResId)
                .setContentTitle(notificationTitle)
                .setContentText(notificationContent)
                .setNumber(3); //久按桌面图标时允许的此条通知的数量

        builder.setLargeIcon(largeIcon);

        PendingIntent pendingIntent = getActivity(context, 0, installIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        Notification notification = builder.build();// 获取一个Notification
        notification.defaults = Notification.DEFAULT_SOUND;// 设置为默认的声音
        notification.flags = isCanClear ? Notification.FLAG_ONLY_ALERT_ONCE : Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_NO_CLEAR;
        manager.notify(downloadNotifcationId, notification);// 显示通知
    }

    /**
     * 展示实时下载进度通知
     *
     * @param context               上下文
     * @param currentProgress       当前进度
     * @param totalProgress         总进度
     * @param notificationIconResId 通知图标资源id
     * @param notificationTitle     通知标题
     * @param isCanClear            通知是否可被清除
     */
    public static void showDownloadingNotification(Context context, int currentProgress, int totalProgress,  Bitmap largeIcon, int notificationIconResId, String notificationTitle, boolean isCanClear) {
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            //ChannelId为"1",ChannelName为"Channel1"
            NotificationChannel channel = new NotificationChannel("1",
                    "Channel1", NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true); //是否在桌面icon右上角展示小红点
            channel.setLightColor(Color.GREEN); //小红点颜色
            channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
            manager.createNotificationChannel(channel);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "1");
        builder.setAutoCancel(true)
                .setShowWhen(true)
                .setOngoing(false)
                .setSmallIcon(notificationIconResId)
                .setContentTitle(notificationTitle).setLargeIcon(largeIcon)
                .setProgress(totalProgress, currentProgress, false);
        Notification notification = builder.build();// 获取一个Notification
        notification.defaults = Notification.DEFAULT_SOUND;// 设置为默认的声音
        notification.flags = isCanClear ? Notification.FLAG_ONLY_ALERT_ONCE : Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_NO_CLEAR;
        manager.notify(downloadNotifcationId, notification);// 显示通知
    }

    /**
     * 展示下载失败通知
     *
     * @param context               上下文
     * @param notificationContent   通知内容,比如:下载失败,点击重新下载
     * @param intent                该intent用来重新下载应用
     * @param notificationIconResId 通知图标资源id
     * @param notificationTitle     通知标题
     * @param isCanClear            通知是否可被清除
     */
    public static void showDownloadFailureNotification(Context context, Intent intent,  Bitmap largeIcon, int notificationIconResId, String notificationTitle, String notificationContent, boolean isCanClear) {
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            //ChannelId为"1",ChannelName为"Channel1"
            NotificationChannel channel = new NotificationChannel("1",
                    "Channel1", NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true); //是否在桌面icon右上角展示小红点
            channel.setLightColor(Color.GREEN); //小红点颜色
            channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
            manager.createNotificationChannel(channel);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "1");
        builder.setAutoCancel(true)
                .setShowWhen(true)
                .setOngoing(false)
                .setSmallIcon(notificationIconResId)
                .setLargeIcon(largeIcon)
                .setContentTitle(notificationTitle).setContentText(notificationContent);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        Notification notification = builder.build();// 获取一个Notification
        notification.defaults = Notification.DEFAULT_SOUND;// 设置为默认的声音
        notification.flags = isCanClear ? Notification.FLAG_ONLY_ALERT_ONCE : Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_NO_CLEAR;
        manager.notify(downloadNotifcationId, notification);// 显示通知
    }

    //判断该app是否打开了通知
    /**
     * 可以通过NotificationManagerCompat 中的 areNotificationsEnabled()来判断是否开启通知权限。NotificationManagerCompat 在 android.support.v4.app包中，是API 22.1.0 中加入的。而 areNotificationsEnabled()则是在 API 24.1.0之后加入的。
     * areNotificationsEnabled 只对 API 19 及以上版本有效，低于API 19 会一直返回true
     * */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static boolean isNotificationEnabled(Context context) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
            boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled();
            return areNotificationsEnabled;
        }

        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;

        Class appOpsClass = null;
        /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }

    //打开手机设置页面
    /**
     * 假设没有开启通知权限，点击之后就需要跳转到 APP的通知设置界面，对应的Action是：Settings.ACTION_APP_NOTIFICATION_SETTINGS, 这个Action是 API 26 后增加的
     * 如果在部分手机中无法精确的跳转到 APP对应的通知设置界面，那么我们就考虑直接跳转到 APP信息界面，对应的Action是：Settings.ACTION_APPLICATION_DETAILS_SETTINGS*/
    public static void gotoSet(Context context) {

        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            // android 8.0引导
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName());
        } else if (Build.VERSION.SDK_INT >= 21) {
            // android 5.0-7.0
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", context.getPackageName());
            intent.putExtra("app_uid", context.getApplicationInfo().uid);
        } else {
            // 其他
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

}
